package com.example.studyspringdemo.biz.impl;


import com.example.studyspringdemo.bean.User;
import com.example.studyspringdemo.biz.UserBiz;
import com.example.studyspringdemo.service.UserService;
import com.example.studyspringdemo.utils.SaltUtils;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Service("UserBiz")
public class UserBizImpl implements UserBiz {
    @Resource
    private UserService userService;

    @Override
    public List<User> selectAll() {
        return userService.selectAll();
    }

    @Override
    public int saveUser(User user) {
        user.setSalt(SaltUtils.getCharAndNumr(5));
        user.setPassword(md5(user.getPassword()+user.getSalt()));
        return userService.saveUser(user);
    }

    @Override
    public boolean checkUserName(String userName) {
        List<User> users =  userService.selectUsersByUserName(userName);
        if(users == null || users.isEmpty()){
            return false;
        }else{
            return true;
        }
    }

    @Override
    public boolean checkEmail(String email) {
        List<User> users =  userService.selectUsersByEmail(email);
        if(users == null || users.isEmpty()){
            return false;
        }else{
            return true;
        }
    }

    public static String md5(String str) {
        String md5 = "  ";
        try {
            md5 = DigestUtils.md5DigestAsHex(str.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return md5;
    }
}
